<?php

    /**
     *      [Discuz!] (C)2001-2099 Comsenz Inc.
     *      This is NOT a freeware, use is subject to license terms
     *      $Id: cloud.class.php 31281 2012-08-03 02:29:27Z zhangjie $
     */

    define("MOBILE_PLUGIN_VERSION", "2");

    class cloud_core {

        function result($result) {
            global $_G;

            // 添加默认输出只有error信息的话，加上规范的Result节点。
            if (!empty($result['error'])) {
                $result = array(
                    'success' => 'true',
                    'Version' => $_GET['version'],
                    'Charset' => 'UTF-8',
                    'Message' => array(
                        "messageval" => $result['error'],
                        "messagestr" => '功能模块不存在！' //lang('plugin/cloud','1006')
                    ),
                    'Result' => array("code" => 1006)
                );
            }


            ob_end_clean();
            function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();

            if (!empty($_GET['callback'])) {
                dheader('Content-Type: application/json');
                echo  $_GET['callback'] . '(' . cloud_core::json($result) . ');';
            } else {
                echo cloud_core::json($result);
            }
            exit;
        }

        function json($encode) {
            if (!empty($_GET['debug']) && defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) {
                return debug($encode);
            }
            require_once 'source/plugin/cloud/json.class.php';
            return CJSON::encode($encode);
        }

        /*
        * 将http传入的json参数，转换成http的参数值
        */
        function jsonToRequest() {
            $request = $_GET['request'];
            if (empty($request)) {
                $request = $_POST['request'];
            }
            if (!empty($request)) {
                require_once 'source/plugin/cloud/json.class.php';
                $json = CJSON::decode(stripslashes($request), true);
                foreach ($json as $key => $value) {
                    $_GET[$key] = $value;
                    $_POST[$key] = $value; //porterzhang 修改 add 将传入参数写入到post中
                }
                $_GET['request'] = "";
                $_POST['request'] = "";
            }
        }

        /*
       * 将登录用户信息查询出来放到$_G中
       */
        /*
       * 将http传入的json参数，转换成http的参数值
       */
        function getLoginUserInfo() {
            global $_G;
            $auth = explode("\t", authcode($_G['cookie']['auth'], 'DECODE'));
            if (!empty($auth[0])) {
                loadcache('cloud_login_user_info');
                $cloud_login_user_info = $_G['cache']['cloud_login_user_info']['login_info'];
                //                echo'<pre>';
                //                print_r($cloud_login_user_info);
                //                exit;
                $_G['cloud_uid'] = $auth[2];
                $_G['cloud_user'] = $cloud_login_user_info[$auth[1] . '_' . $auth[2]];
            }
        }

        function getvalues($variables, $keys, $subkeys = array()) {
            $return = array();
            foreach ($variables as $key => $value) {
                foreach ($keys as $k) {
                    if ($k{0} == '/' && preg_match($k, $key) || $key == $k) {
                        if ($subkeys) {
                            $return[$key] = cloud_core::getvalues($value, $subkeys);
                        } else {
                            if (!empty($value) || !empty($_GET['debug']) || (is_numeric($value) && intval($value) === 0)) {
                                $return[$key] = is_array($value) ? cloud_core::arraystring($value) : (string)$value;
                            } else {
                                $return[$key] = '';
                            }
                        }
                    }
                }
            }
            return $return;
        }

        function arraystring($array) {
            foreach ($array as $k => $v) {
                $array[$k] = is_array($v) ? cloud_core::arraystring($v) : (string)$v;
            }
            return $array;
        }

        function variable($variables = array()) {
            global $_G;
            $globals = array(
                'cookiepre' => $_G['config']['cookie']['cookiepre'],
                'auth' => "" . $_G['cookie']['auth'],
                'saltkey' => $_G['cookie']['saltkey'],
                'member_uid' => "" . $_G['cloud_uid'],
                'member_username' => "" . $_G['cloud_user']['name'],
                'avatar' => empty($_G['cloud_user']['headphoto']) ? $_G['siteurl'] . 'uc_server/avatar.php?size=middle&uid=0' : $_G['siteurl'] . $_G['cloud_user']['headphoto'],
                'isadmin' => empty($_G['cloud_user']['isadmin']) ? '0' : '' . $_G['cloud_user']['isadmin'],
                'admintype' => empty($_G['cloud_user']['admintype']) ? '0' : '' . $_G['cloud_user']['admintype'], //管理员类型
                'department' => empty($_G['cloud_user']['areaId']) ? '0' : '' . $_G['cloud_user']['areaId'], //管理员是区域管理员还是app管理员
                'app_id' => empty($_G['cloud_user']['app']['caid']) ? '0' : '' . $_G['cloud_user']['app']['caid'],
                'app_name' => empty($_G['cloud_user']['app']['name']) ? '' : '' . $_G['cloud_user']['app']['name'],
            );
            if (!empty($_GET['submodule']) == 'checkpost') {
                $apifile = 'source/plugin/cloud/api/' . $_GET['version'] . '/sub_checkpost.php';
                if (file_exists($apifile)) {
                    require_once $apifile;
                    $globals = $globals + cloud_api_sub::getvariable();
                }
            }

            $xml = array(
                'success' => true,
                'Version' => $_GET['version'],
                'Charset' => strtoupper($_G['charset']),
                'Variables' => array_merge($globals, $variables),
            );
            if (!empty($_G['messageparam'])) {
                $message_result = lang('plugin/cloud', $_G['messageparam'][0], $_G['messageparam'][2]);
                if ($message_result == $_G['messageparam'][0]) {
                    $vars = explode(':', $_G['messageparam'][0]);
                    if (count($vars) == 2) {
                        $message_result = lang('plugin/' . $vars[0], $vars[1], $_G['messageparam'][2]);
                        $_G['messageparam'][0] = $vars[1];
                    } else {
                        $message_result = lang('message', $_G['messageparam'][0], $_G['messageparam'][2]);
                    }
                }
                $message_result = strip_tags($message_result);

                if ($_G['messageparam'][4]) {
                    $_G['messageparam'][0] = "custom";
                }
                if ($_G['messageparam'][3]['login'] && !$_G['uid']) {
                    $_G['messageparam'][0] .= '//' . $_G['messageparam'][3]['login'];
                }
                $xml['Message'] = array("messageval" => $_G['messageparam'][0], "messagestr" => $message_result);
                if ($_GET['mobilemessage']) {
                    $return = cloud_core::json($xml);
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location:discuz://" . rawurlencode($_G['messageparam'][0]) . "//" .
                        rawurlencode(diconv($message_result, $_G['charset'], "utf-8")) . ($return ? "//" . rawurlencode($return) : ''));
                    exit;
                }
            }
            // 返回Result值，默认返回0；
            // 判断是否有错误，有错误的返回错误码
            $xml['Variables']['Result'] = array("code" => 0);
            if (!empty($xml['Message'])) {
                $errval = $xml['Message']['messageval'];
                if (strpos($errval, 'succeed') == false && strpos($errval, 'success') == false) {
                    $xml['Variables']['Result'] = array("code" => 9999);
                }
            }

            if (!empty($variables['code'])) {
                $xml['Variables']['Result'] = array("code" => $variables['code']);
                unset($xml['Variables']['code']);
            }
            if (!empty($variables['messagestr'])) {
                $xml['Variables']['Message'] = array("messagestr" => $variables['messagestr']);
                unset($xml['Variables']['messagestr']);
            }
            return $xml;
        }


    }

    class base_plugin_cloud {

        function common() {
            if (!defined('IN_MOBILE_API')) {
                return;
            }
            global $_G;
            if (!empty($_GET['tpp'])) {
                $_G['tpp'] = intval($_GET['tpp']);
            }
            if (!empty($_GET['ppp'])) {
                $_G['ppp'] = intval($_GET['ppp']);
            }
            $_G['siteurl'] = preg_replace('/api\/cloud\/$/', '', $_G['siteurl']);
            $_G['setting']['msgforward'] = '';
            $_G['setting']['cacheindexlife'] = $_G['setting']['cachethreadlife'] = false;
            if (class_exists('cloud_api', 'common')) {
                cloud_api::common();
            }
        }

        function discuzcode() {
            if (!defined('IN_MOBILE_API')) {
                return;
            }
            global $_G;
            $_G['discuzcodemessage'] = preg_replace(array(
                "/\[size=(\d{1,2}?)\]/i",
                "/\[size=(\d{1,2}(\.\d{1,2}+)?(px|pt)+?)\]/i",
                "/\[\/size]/i",
            ), '', $_G['discuzcodemessage']);
        }

        function global_cloud() {
            if (!defined('IN_MOBILE_API')) {
                return;
            }
            if (class_exists('cloud_api', 'output')) {
                cloud_api::output();
            }
        }

    }

    class base_plugin_cloud_forum extends base_plugin_cloud {

        function post_cloud_message($param) {
            if (!defined('IN_MOBILE_API')) {
                return;
            }
            if (class_exists('cloud_api', 'post_cloud_message')) {
                list($message, $url_forward, $values, $extraparam, $custom) = $param['param'];
                cloud_api::post_cloud_message($message, $url_forward, $values, $extraparam, $custom);
            }
        }

        function viewthread_postbottom_output() {
            global $_G, $postlist;
            foreach ($postlist as $k => $post) {
                $frommobiletype = '';
                if ($post['mobiletype'] == 1) {
                    $frommobiletype = lang('plugin/cloud', 'mobile_fromtype_ios');
                } elseif ($post['mobiletype'] == 2) {
                    $frommobiletype = lang('plugin/cloud', 'mobile_fromtype_android');
                } elseif ($post['mobiletype'] == 3) {
                    $frommobiletype = lang('plugin/cloud', 'mobile_fromtype_windowsphone');
                }
                $post['message'] .= $frommobiletype ? '<br><a href="misc.php?mod=mobile" target="_blank" style="font-size:12px;color:#708090;">'
                    . $frommobiletype . '</a>' : '';
                $postlist[$k] = $post;
            }
            return array();
        }

    }

    class base_plugin_cloud_misc extends base_plugin_cloud {

        function mobile() {
            global $_G;
            if (empty($_GET['view']) && !defined('MOBILE_API_OUTPUT')) {
                $_G['setting']['pluginhooks'] = array();
                $qrfile = DISCUZ_ROOT . './data/cache/mobile_siteqrcode.png';
                if (!file_exists($qrfile) || $_G['adminid'] == 1) {
                    require_once DISCUZ_ROOT . 'source/plugin/cloud/qrcode.class.php';
                    QRcode::png($_G['siteurl'], $qrfile);
                }
                define('MOBILE_API_OUTPUT', 1);
                $_G['disabledwidthauto'] = 1;
                define('TPL_DEFAULT', true);
                include template('cloud:mobile');
                exit;
            }
        }

    }

    class plugin_cloud extends base_plugin_cloud {
        //将登录用户信息放入到$_G中
        function setLoginStatus($user, $userType, $areaId = 0) {
            global $_G;
            //add porterzhang 设置cookie失效时间
            $cookieTime = 60 * 60 * 24 * 7;
            if ($userType == 'manage') {
                $user['isadmin'] = '1';
                $user['admintype'] = $user['type'];
                $user['areaId'] = $areaId;
            } else {
                $user['isadmin'] = '0';
                $user['admintype'] = '0';
                $user['deparea'] = '';
                $user['areaId'] = $areaId;
            }
            $cloud_uid = ($userType == 'manage') ? $user['camid'] : $user['cuid'];
            //将登录用户的信息存放到cache中，方便以后取数据方便
            loadcache('cloud_login_user_info');

            $cloud_login_user_info = array();
            if ($_G['cache']['cloud_login_user_info']['login_info']) {
                $cloud_login_user_info = $_G['cache']['cloud_login_user_info']['login_info'];
            }
            $login_user = array(
                $userType . '_' . $cloud_uid => $user
            );
            $cloud_login_user_info = array_merge($cloud_login_user_info, $login_user);
            savecache('cloud_login_user_info', array('login_info' => $cloud_login_user_info, 'expiration' => TIMESTAMP));
            //-----------------------------
            $_G['cloud_uid'] = $cloud_uid;
            $_G['cloud_user'] = $user;
            C::app()->session->isnew = true;
            C::app()->session->updatesession();
            dsetcookie('auth', authcode("{$user['password']}\t{$userType}\t{$cloud_uid}", 'ENCODE'), $cookieTime, 1, true);
            dsetcookie('loginuser');
            dsetcookie('activationauth');
            dsetcookie('pmnum');
        }

        //将登录用户信息在cache中清除
        function setLoginOut($userType, $userId) {
            global $_G;
            //将登录用户的信息存放到cache中，方便以后取数据方便
            loadcache('cloud_login_user_info');
            $cloud_login_user_info = $_G['cache']['cloud_login_user_info']['login_info'];
            unset($cloud_login_user_info[$userType . '_' . $userId]);
            savecache('cloud_login_user_info', array('login_info' => $cloud_login_user_info, 'expiration' => TIMESTAMP));
            //-----------------------------
        }

        //上传初始化
        function update_init($attach, $type = 'temp', $extid = 0, $forcename = '') {

            $extid = intval($extid);
            $attach['size'] = intval($attach['size']);

            if (empty($attach['size'])) {
                self::uploadMsg(1024);
            }
            $attach['name'] = trim($attach['name']);
            $attach['thumb'] = '';
            $attach['ext'] = self::fileExt($attach['name']);
            if (!self::is_update_type($attach['ext'])) {
                self::uploadMsg(1023);
            }

            $attach['name'] = dhtmlspecialchars($attach['name'], ENT_QUOTES);
            if (strlen($attach['name']) > 90) {
                $attach['name'] = cutstr($attach['name'], 80, '') . '.' . $attach['ext'];
            }
            $attach['isimage'] = self::is_image_ext($attach['ext']);
            $attach['extension'] = self::get_target_extension($attach['ext']);
            $attach['attachdir'] = self::get_target_dir($type, $extid);
            $attach['attachment'] = $attach['attachdir'] . self::get_target_filename($type, $extid, $forcename) . '.' . $attach['extension'];
            $attach['target'] = getglobal('setting/attachdir') . $type . '/' . $attach['attachment'];
//            $attach['target'] =  'E://wamp/server/data' . $attach['attachment'];


            return $attach;
        }

        //保存上传的文件
        function saveUpload($attach) {
            $source = $attach['tmp_name'];
            $target = $attach['target'];
            if (!discuz_upload::is_upload_file($source)) {
                $succeed = false;
            } elseif (@copy($source, $target)) {
                $succeed = true;
            } elseif (function_exists('move_uploaded_file') && @move_uploaded_file($source, $target)) {
                $succeed = true;
            } elseif (@is_readable($source) && (@$fp_s = fopen($source, 'rb')) && (@$fp_t = fopen($target, 'wb'))) {
                while (!feof($fp_s)) {
                    $s = @fread($fp_s, 1024 * 512);
                    @fwrite($fp_t, $s);
                }
                fclose($fp_s);
                fclose($fp_t);
                $succeed = true;
            }
            if ($succeed) {
                @chmod($target, 0644);
                @unlink($source);
            }
            //判断是否上传成功
            if (!$succeed) {
                self::uploadMsg(1025);
            }
        }

        //上传提示
        function uploadMsg($statusid, $attachid = 0) {
            if ($statusid > 0) {
                $variable = array(
                    'code' => intval($statusid),
                    'messagestr' => lang('plugin/cloud', '' . $statusid),
                );
            } else {
                $variable = array(
                    'data' => array(
                        'attachid' => $attachid
                    )
                );
            }
            cloud_core::result(cloud_core::variable($variable));
        }
        //上传提示
        function uploadOtherMsg($statusid, $attachdir) {
            if ($statusid > 0) {
                $variable = array(
                    'code' => intval($statusid),
                    'messagestr' => lang('plugin/cloud', '' . $statusid),
                );
            } else {
                $variable = array(
                    'data' => array(
                        'attachdir' => $attachdir,
                    )
                );
            }
            cloud_core::result(cloud_core::variable($variable));
        }

        //判断是否能够上传的文件
        function is_update_type($ext) {
            static $update_type = array('attach', 'jpg', 'jpeg', 'gif', 'png', 'bmp', 'mp3', 'm4a', 'wav');
            return in_array($ext, $update_type) ? 1 : 0;
        }

        //判断是否是图片
        function is_image_ext($ext) {
            static $imgext = array('jpg', 'jpeg', 'gif', 'png', 'bmp');
            return in_array($ext, $imgext) ? 1 : 0;
        }

        //判断是否为其他文件
        function get_target_extension($ext) {
            static $safeext = array('attach', 'jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp', 'txt', 'zip', 'rar', 'mp3');
            return strtolower(!in_array(strtolower($ext), $safeext) ? 'attach' : $ext);
        }

        //创建上传的地址
        function get_target_dir($type, $extid = '', $check_exists = true) {
            $subdir = $subdir1 = $subdir2 = '';
            if ($type == 'album' || $type == 'forum' || $type == 'portal' || $type == 'category' || $type == 'profile'
                || $type == 'product' || $type == 'article' || $type == 'adpic' || $type == 'richtext'
            ) {
                $subdir1 = date('Ym');
                $subdir2 = date('d');
                $subdir = $subdir1 . '/' . $subdir2 . '/';
            } elseif ($type == 'group' || $type == 'common') {
                $subdir = $subdir1 = substr(md5($extid), 0, 2) . '/';
            }
            $check_exists && discuz_upload::check_dir_exists($type, $subdir1, $subdir2);
            return $subdir;
        }

        //得到file的文件名
        function get_target_filename($type, $extid = 0, $forcename = '') {
            if ($type == 'group' || ($type == 'common' && $forcename != '')) {
                $filename = $type . '_' . intval($extid) . ($forcename != '' ? "_$forcename" : '');
            } else {
                $filename = date('His') . strtolower(random(16));
            }
            return $filename;
        }

        //得到后缀名
        function fileExt($filename) {
            return addslashes(strtolower(substr(strrchr($filename, '.'), 1, 10)));
        }

        //错误信息提示
        function showMessage($code) {
            $variable = array(
                'code' => intval($code),
                'messagestr' => lang('plugin/cloud', '' . $code),
            );
            cloud_core::result(cloud_core::variable($variable));
        }

        //成功信息提示
        function showSuccessMessage($code) {
            $variable = array(
                'messagestr' => lang('plugin/cloud', '' . $code),
            );
            cloud_core::result(cloud_core::variable($variable));
        }
    }

    class plugin_cloud_forum extends base_plugin_cloud_forum {
    }

    class plugin_cloud_misc extends base_plugin_cloud_misc {
    }

    class mobileplugin_cloud extends base_plugin_cloud {
        function global_header_cloud() {
            $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
            if (strpos($useragent, 'iphone') !== false || strpos($useragent, 'ios') !== false) {
                return lang('plugin/cloud', 'mobile_tip_ios');
            } elseif (strpos($useragent, 'android') !== false) {
                return lang('plugin/cloud', 'mobile_tip_android');
            } elseif (strpos($useragent, 'windows phone') !== false) {
                return lang('plugin/cloud', 'mobile_tip_wp7');
            }
        }
    }

    class mobileplugin_cloud_forum extends base_plugin_cloud_forum {
    }

    class mobileplugin_cloud_misc extends base_plugin_cloud_misc {
    }

    class plugin_cloud_connect extends plugin_cloud {

        function login_cloud_message($param) {
            if (substr($_GET['referer'], 0, 7) == 'Mobile_') {
                if ($_GET['referer'] == 'Mobile_iOS' || $_GET['referer'] == 'Mobile_Android') {
                    $_GET['mobilemessage'] = 1;
                }
                global $_G;
                $param = array('con_auth_hash' => $_G['cookie']['con_auth_hash']);
                cloud_core::result(cloud_core::variable($param));
            }
        }

    }


